using System.Linq;
using Admin3000.Backend.Api.Entity;
using Admin3000.Backend.Api.Params;
using Admin3000.Backend.Api.Repository;
using Admin3000.Backend.Api.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace Admin3000.Backend.Api.Controllers
{
    // [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class UsersController : ControllerBase
    {
        private IConfiguration _configuration;

        private IRepository<Users> _usersRepository;

        private TokenParameter _tokenParameter;

        public UsersController(
            IConfiguration configuration,
            IRepository<Users> usersRepository
        )
        {
            _configuration = configuration;
            _usersRepository = usersRepository;
            _tokenParameter =
                _configuration
                    .GetSection("TokenParameter")
                    .Get<TokenParameter>();
        }


        //列出用户列表
        [HttpGet]
        public string Get([FromQuery] QueryWithPager query)
        {
            // get请求默认从url中获取参数，如果需要使用实体接收参数，需要FromQuery特性
            var pageIndex = query.Pager.PageIndex;
            var pageSize = query.Pager.PageSize;
            var keyword = string.IsNullOrEmpty(query.Keyword) ? "" : query.Keyword.Trim();
            var users = _usersRepository.Table
            .Where(x => x.IsDeleted == false);
            // 如果keyword不为空，则再去查询用户名
            if (!string.IsNullOrEmpty(keyword))
            {
                users = users.Where(x => x.Username.Contains(keyword));
            }

            var u = users.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            var res = new
            {
                Code = 1000,
                Data = new { Data = u, Pager = new { pageIndex, pageSize, rowsTotal = users.Count() } },
                Msg = "获取用户列表成功^_^"
            };
            return JsonHelper.Serialize(res);
        }


        //获取用户数量
        [HttpGet("homepage"), Route("homepage")]
        public dynamic homepage()
        {
            var users = _usersRepository.Table.ToList();
            var res = new
            {
                Code = 1000,
                Data = new { Data = users },
                Msg = "获取用户列表成功^_^"
            };

            return JsonHelper.Serialize(res);
        }

        //查询对应Id用户
        [HttpGet("{id}")]
        public dynamic Get(int id)
        {
            var user = _usersRepository.GetById(id);

            if (user == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "你要查询的用户不存在！"
                };
            }
            return JsonHelper.Serialize(new
            {
                Code = 1000,
                Data = user,
                Msg = "获取指定用户成功"
            });

        }


        //新增用户
        [HttpPost]
        public dynamic Post([FromBody] CreateUser newUser)
        {
            var username = newUser.Username.Trim();
            var password = newUser.Password == null ? "113" : newUser.Password.Trim();

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)
            )
            {
                return JsonHelper.Serialize(new { Code = 104, Data = " ", Msg = "用户名或密码不能为空" });
            }

            var user =
                new Users
                {
                    Username = newUser.Username,
                    Password = newUser.Password,
                    Remarks = newUser.remarks
                };

            _usersRepository.Insert(user);
            return JsonHelper.Serialize(new { Code = 1000, Data = user, Msg = "创建用户成功^_^" });
        }


        //修改对应Id用户
        [HttpPut("{id}")]
        public string Put(int id, CreateUser updateUser)
        {
            var username = updateUser.Username.Trim();
            var password = updateUser.Password.Trim();

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)
            )
            {
                return JsonHelper.Serialize(new
                {
                    Code = 104,
                    Data = "",
                    Msg = "用户名或密码不能为空=_="
                });
            }

            var user = _usersRepository.GetById(id);

            if (user == null)
            {
                return JsonHelper.Serialize(new
                {
                    Code = 104,
                    Data = "",
                    Msg = "要更新的用户不存在，请确认后重试=_="
                });
            }

            user.Username = updateUser.Username;
            user.Password = updateUser.Password;
            user.Remarks = updateUser.remarks;

            _usersRepository.Update(user);

            return JsonHelper.Serialize(new { Code = 1000, Data = user, Msg = "更新成功" });
        }





        //删除对应Id用户
        [HttpDelete("{id}")]
        public dynamic Delete(int id)
        {
            _usersRepository.Delete(id);
            return new { Code = 1000, Data = "", Msg = "删除用户成功^_^" };
        }




        //登录验证 获取token
        [AllowAnonymous]
        [HttpPost, Route("token")]
        public dynamic GetToken(CreateUser newUser)
        {
            var username = newUser.Username.Trim();
            var password = newUser.Password.Trim();

            var user =
                _usersRepository
                    .Table
                    .Where(x =>
                        x.Username == username && x.Password == password)
                    .FirstOrDefault();

            if (user == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "用户名或密码不正确，请确认后重试"
                };
            }

            var token =
                TokenHelper.GenerateToekn(_tokenParameter, user.Username);
            var refreshToken = "112358";

            return new
            {
                Code = 1000,
                Data = new { Token = token, refreshToken = refreshToken, user.Username, user.Password, user.Id },
                Msg = "用户登录成功^_^"
            };
        }


        //刷新frfreshtoken
        [AllowAnonymous]
        [HttpPost, Route("refreshtoken")]
        public dynamic RefreshToken(RefreshTokenDTO refresh)
        {
            var username = TokenHelper.ValidateToken(_tokenParameter, refresh);

            if (string.IsNullOrEmpty(username))
            {
                return new { Code = 1002, Data = "", Msg = "token验证失败" };
            }

            var token = TokenHelper.GenerateToekn(_tokenParameter, username);
            var refreshToken = "112358";

            return new
            {
                Code = 1000,
                Data = new { Token = token, refreshToken = refreshToken },
                Msg = "刷新token成功^_^"
            };
        }
    }
}
